<?php
/**
 * Session类
*/

namespace houze;

class Session {
    /**
     * 前缀
    */
    private static $session_prefix;
    /**
     * 过期时间
    */
    private static $session_outtime;
    /**
     * SessionID
    */
    private static $session_id;

    /**
     * 是否存在
    */
    public static function has($key) {
        self::config();
        $redis = new \houze\Redis();

        $key = self::$session_id.'_'.self::$session_prefix.$key;
        if (!empty($redis->get($key))) {
            $redis->return();
            return true;
        }

        $redis->return();
        return false;
    }

    /**
     * 读取
    */
    public static function get($key) {
        self::config();
        $redis = new \houze\Redis();

        $key = self::$session_id.'_'.self::$session_prefix.$key;
        if (!empty($redis->get($key))) {
            $data = json_decode($redis->get($key), true);
            $redis->return();
            return $data;
        }

        $redis->return();
        return false;
    }

    /**
     * 写入
    */
    public static function set($key, $val, $time=null) {
        self::config();
        $redis = new \houze\Redis();

        $key = self::$session_id.'_'.self::$session_prefix.$key;
        if (empty($time)) {
            $time = self::$session_outtime;
        }
        $time += time();

        $val = json_encode($val);

        $redis->set($key, $val);
        $redis->expireat($key, $time);
        $redis->return();

        return true;
    }

    /**
     * 删除
    */
    public static function delete($key) {
        self::config();
        $redis = new \houze\Redis();
        $key = self::$session_id.'_'.self::$session_prefix.$key;

        if ($redis->del($key)) {
            $redis->return();
            return true;
        }

        $redis->return();
        return false;
    }

    /**
     * 清空
    */
    public static function clear() {
        self::config();
        $redis = new \houze\Redis();
        $key = self::$session_id.'_'.self::$session_prefix.'*';
        $list = $redis->keys($key);
        $ret = $redis->del($list);
        $redis->return();
        return $ret;
    }

    /**
     * 初始化配置
    */
    private static function config() {
        $Request = \houze\context\Request::get();
        self::$session_id = $Request->cookie['PHPSESSID'];
        self::$session_prefix = \houze\Config::get('app.session_prefix');
        self::$session_outtime = \houze\Config::get('app.session_outtime');
    }
}